package org.apache.commons.exec.io;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

public class InputStreamWriter extends InputStream {
	//private final static Logger LOGGER = LoggerFactory.getLogger(InputStreamWriter.class);
	private BlockingQueue<Byte> buffer;
	private Charset charset = Charset.forName("UTF-8");

	public InputStreamWriter() {
		this(8192, Charset.forName("UTF-8"));
	}

	public InputStreamWriter(int capacity, Charset charset) {
		super();
		this.charset = charset;
		buffer = new LinkedBlockingQueue<>(capacity);
	}

	@Override
	public int read() throws IOException {
		//LOGGER.debug("read()");
		try {
			return buffer.take();
		} catch (InterruptedException e) {
			throw new IOException();
		}
	}

	public void write(String src) throws IOException {
		byte[] bytes=src.getBytes(charset);
		write(bytes);
	}
	
	public void write(byte[] bytes) throws IOException{
		for(byte b:bytes) {
			try {
				buffer.put(b);
			} catch (InterruptedException e) {
				throw new IOException();
			}
		}
		//LOGGER.debug("new buffer size: {}", buffer.size());
	}

	@Override
	public int available() throws IOException {
		return 1;//TODO always valid
	}
	
	public void flush() {
		
	}
	
}
